package my.suveng.model.common.response;

import cn.hutool.core.lang.caller.CallerUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import my.suveng.model.common.interfaces.response.IMessage;
import my.suveng.model.common.interfaces.response.IMessageBuilder;
import my.suveng.model.common.response.base.BaseMessageBuilder;
import my.suveng.util.log.PlusLogFactoryHutool;

/**
 * 使用入口, 类似fastjson的 JSON
 * @author suwenguang
 **/
public abstract class Message {
    //hutool日志
    private static final Log log = LogFactory.setCurrentLogFactory(new PlusLogFactoryHutool()).getLog(CallerUtil.getCaller().getName());

    /**
     * 默认
     */
    protected static IMessageBuilder messageBuilder = BaseMessageBuilder.INSTANCE;

    public static IMessageBuilder getMessageBuilder() {
        return messageBuilder;
    }

    /**
     * 配置构建器,一次配置,后面都会使用配置过的构建起,慎重
     * @param messageBuilder 构建器
     */
    public static void configureMessageBuilder(Class<? extends IMessageBuilder> messageBuilder) {
        IMessageBuilder instance;
        try {
            instance = messageBuilder.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            //e.printStackTrace();
            log.error("设置失败!", e);
            return;
        }
        Message.messageBuilder = instance;
    }

    public static <T> IMessage<T> build(boolean success, String message, T data) {
        return messageBuilder.build(success, message, data);
    }

    public static <T> IMessage<T> error(String message) {
        return messageBuilder.errorWithMessage(message);
    }

    public static <T> IMessage<T> success() {
        return messageBuilder.successWithData(null);
    }

    public static <T> IMessage<T> successWithData(T data) {
        return messageBuilder.successWithData(data);
    }

    public static <T> IMessage<T> build(boolean success, String message, T data, Object... params) {
        return messageBuilder.build(success, message, data, params);
    }
}
